const express = require("express")
const { discriminator, find, findOne } = require("../../../db/user")
const router = express.Router()
const multer = require("multer")
const path = require("path")
const { join } = require("path")
const fs = require("fs")
const userDB = require("../../../db/user")
const { sensitiveVer } = require('../../../utils/sensitiveVerification')

// 用户注册
router.post("/reg", async (req, res) => {
  try {
    let { name, pass } = req.body
    if (!name.trim()) {
      return res.send({
        code: 5,
        mes: "用户名格式不正确"
      })
    }
    if (!pass.trim()) {
      return res.send({
        code: 5,
        mes: "密码格式不正确"
      })
    }
    // 检测用户名是否存在
    let doc = await userDB.findOne({ name })
    if (doc) {
      return res.send({
        code: 5,
        mes: "该用户已被注册"
      })
    }

    await sensitiveVer(name)

    // 添加
    await userDB.create({ name, pass })
    res.send({
      code: 0,
      mes: "用户注册成功，已跳转到登录页面"
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: error || "服务器异常，请稍后再试"
    })
  }
})

// 用户登录
router.post("/login", async (req, res) => {
  try {
    let { name, pass } = req.body
    if (!name.trim()) {
      return res.send({
        code: 5,
        mes: "用户名格式不正确"
      })
    }
    if (!pass.trim()) {
      return res.send({
        code: 5,
        mes: "密码格式不正确"
      })
    }
    // 检测用户名是否存在
    let doc = await userDB.findOne({ name })
    if (!doc) {
      return res.send({
        code: 5,
        mes: "该用户名不存在，请先注册"
      })
    }
    // 存入session
    req.session.userInfo = doc
    // 存入vuex
    let userInfoVuex = {
      name: doc.name,
      _id: doc._id,
      phone: doc.phone,
      collectionJournal: doc.collectionJournal,
      collectionShare: doc.collectionShare
    }
    res.send({
      code: 0,
      mes: "登录成功，欢迎回来",
      data: userInfoVuex
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试"
    })
  }
})

// 检测是否登录
router.post("/judge", async (req, res) => {
  try {
    if (!req.session.userInfo) {
      return res.send({
        code: 5,
        mes: "用户未登录"
      })
    }
    // 更新数据
    let doc = await userDB.findById(req.session.userInfo._id)
    // 更新session
    req.session.userInfo = doc
    // 更新vuex
    let userInfoVuex = {
      name: doc.name,
      _id: doc._id,
      phone: doc.phone,
      collectionJournal: doc.collectionJournal,
      collectionShare: doc.collectionShare
    }
    res.send({
      code: 0,
      mes: "用户已登录",
      data: userInfoVuex
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试"
    })
  }
})


router.use((req, res, next) => {
  if (!req.session.userInfo) {
    return res.send({
      code: 4,
      mes: "请先登录"
    })
  }
  next()
})

// 退出登录
router.post("/exit", async (req, res) => {
  try {
    // 销毁session
    req.session.destroy()
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试"
    })
  }
})

// 修改用户名
router.post("/altname", async (req, res) => {
  try {
    let { name } = req.body
    if (!name) {
      return res.send({
        code: 5,
        mes: "用户名格式不正确"
      })
    }
    let doc = await userDB.findOne({ name })
    if (doc) {
      return res.send({
        code: 5,
        mes: "该用户名已被注册"
      })
    }

    await sensitiveVer(name)

    await userDB.findByIdAndUpdate(req.session.userInfo._id, {
      name
    })
    let newData = await userDB.findById(req.session.userInfo._id)
    // 更新session
    req.session.userInfo = newData
    // 更新vuex
    let userInfoVuex = {
      name: newData.name,
      _id: newData._id,
      phone: newData.phone,
      collectionJournal: newData.collectionJournal,
      collectionShare: newData.collectionShare
    }
    res.send({
      code: 0,
      mes: "用户名修改成功",
      data: userInfoVuex
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: error || "服务器异常，请稍后再试"
    })
  }
})


// 上传cover文件
let coverUpload = multer({
  storage: multer.diskStorage({
    // 文件存储的目录
    destination(req, file, cb) {
      cb(null, join(__dirname, "../../../static/file/phone"))
    },
    // 文件的名字
    filename(req, file, cb) {
      let name = req.session.userInfo._id
      let ext = path.extname(file.originalname)
      req.coverFile = "phone" + name + Date.now() + ext
      cb(null, req.coverFile)  //名字
    }
  })
}).single("file") //name名字 elemetUI默认为file


// 修改密码
router.post("/altpass", async (req, res) => {
  try {
    let { oldPass, pass } = req.body
    let doc = await userDB.findById(req.session.userInfo._id)
    if (doc.pass !== oldPass) {
      return res.send({
        code: 5,
        mes: "原密码不正确"
      })
    }
    await userDB.findByIdAndUpdate(req.session.userInfo._id, {
      pass
    })
    let newData = await userDB.findById(req.session.userInfo._id)
    // 更新session
    req.session.userInfo = newData
    // 更新vuex
    let userInfoVuex = {
      name: newData.name,
      _id: newData._id,
      phone: newData.phone,
      collectionJournal: newData.collectionJournal,
      collectionShare: newData.collectionShare
    }
    req.session.destroy()
    res.send({
      code: 0,
      mes: "密码修改成功",
      data: userInfoVuex
    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试"
    })
  }
})


// 修改头像
router.post("/altphone", async (req, res) => {
  try {
    let _id = req.session.userInfo._id
    coverUpload(req, res, async err => {
      let doc = await userDB.findById(_id)
      // 检测是否上传成功
      if (err) {
        return res.send({
          code: 8,
          mes: "头像上传失败,请刷新后重试"
        })
      }
      // 更改数据库  //删除
      await userDB.findByIdAndUpdate(_id, {
        phone: `/file/phone/` + req.coverFile
      })
      let newData = await userDB.findById(req.session.userInfo._id)
      // 更新session
      req.session.userInfo = newData
      // 更新vuex
      let userInfoVuex = {
        name: newData.name,
        _id: newData._id,
        phone: newData.phone,
        collectionJournal: newData.collectionJournal,
        collectionShare: newData.collectionShare
      }
      res.send({
        code: 0,
        mes: "头像已更换",
        data: userInfoVuex
      })

    })
  } catch (error) {
    res.send({
      code: 5,
      mes: "服务器异常，请稍后再试"
    })
  }
})
module.exports = router